package com.example.blemulticondemo.utils;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;

import com.example.blemulticondemo.bean.SerialPortPackage;
import com.example.blemulticondemo.event.CommonEvent;
import com.example.blemulticondemo.event.EventCode;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;

/**
 * @author linvisf
 * @date 2024/8/6.
 * description：
 */
public class BluetoothResponseUtil {
    private static String result = "";//收到的临时数据
    private static boolean isStartGet = false;// 开始接受数据标志

    public static void handleSerialData(Context context, BluetoothDevice device, String data) {
        result += data;
        if (!isStartGet) {
            if (result.length() < 4) {//太短，55 AA都没有
                return;
            }
            while (result.length() >= 4) {
                if (result.startsWith("55AA")) {
                    break;
                } else {
                    result = result.substring(2, result.length());//移除前面的垃圾数据
                }
            }
            if (result.length() < 4) {//不是55AA开头的
                return;
            }
            isStartGet = true;//开始拼接数据了
            MyReceiveTimer.getInstance().setTimerStart(new MyReceiveTimer.TimerOutCallBack() {
                @Override
                public void timerOver() {
                    Log.i("My", "=========MyReceiveTimer. isOVER:" + result);
                    result = "";
                    isStartGet = false;
                }
            }, 8000);
        }
        if (result.length() < 24) { //还没够一包，返回
            return;
        } else {//可能够一包数据
            while (result.length() > 24) {
                byte[] bResultArray = StringTransformUtil.stringToByte(result);
                int index = 2;
                int len = (bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF);
                if (bResultArray.length >= len + 4) { // 4为55AA+length（2个字节）
                    MyReceiveTimer.getInstance().setTimerCancel();
                    byte packType = bResultArray[index++];//包类型
                    byte packNumber = bResultArray[index++];//包号
                    byte sourceUnit = bResultArray[index++]; //源单元
                    byte descUnit = bResultArray[index++]; //目标单元
                    byte cmd = bResultArray[index++];//命令IDc
                    byte cmdSub = bResultArray[index++];//命令子ID
                    //校验和处理
                    byte crc16Hight = bResultArray[len + 4 - 2];
                    byte crc16Low = bResultArray[len + 4 - 1];
                    int calCrc16 = 0;
                    try {
                        calCrc16 = CRC16.GetCRC16(Arrays.copyOfRange(bResultArray, 4, len + 4 - 2));
                    } catch (Exception e) {
                        Log.e("F400", ".......CRC16...Error  calCrc16异常  ...." + e.getMessage());
                        result = "";
                        isStartGet = false;
                        return;//数据有误，扔掉，重新读
                    }
                    byte calCrc16H = (byte) (calCrc16 >> 8);
                    byte calCrc16L = (byte) (calCrc16);
                    if (crc16Hight != calCrc16H || crc16Low != calCrc16L) {
                        Log.i("DO", ".......CRC16...Error....");
                        result = "";
                        isStartGet = false;
                        return;//数据有误，扔掉，重新读
                    } else {
                        Log.i("DO", ".......CRC16...OK....  ");
                        SerialPortPackage serialPortPackage = new SerialPortPackage();
                        serialPortPackage.setCmd(cmd);
                        serialPortPackage.setCmdSub(cmdSub);
                        serialPortPackage.setSourceUnit(sourceUnit);
                        serialPortPackage.setDescUnit(descUnit);
                        /**************数据处理*************/
                        if (packType == 0x02) {
                            SendTimer.getInstance().setSendTimeOutCancel();
                            //应答包
                            Log.e("DO", ".......Get ACK Package." + bResultArray[index++]);
                        } else if (packType == 0x03) {
                            //结果包
                            Log.e("DO", ".......Get Result Package.");
                            Protocol.sendACK(context, device, cmd, cmdSub, packNumber, (byte) 0x00);
                            byte bResult = bResultArray[index++];
                            serialPortPackage.setResult(bResult);
                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_RESULT_PACKAGE, serialPortPackage));

                        }else if (packType == 0x04) {//数据包
                            if (!(cmd == 0x11 && cmdSub == 0x03) && !(cmd == 0x11 && cmdSub == 0x04)){
//                                Log.e("F400","=== 非11 03 应答包 ===");
                                Protocol.sendACK(context, device, cmd, cmdSub, packNumber, (byte) 0x00);
                            }
                            switch (cmd) {
                                case 0x02://升级命令
                                    switch (cmdSub) {
                                        case 0x00:
                                            String strHardWareVersion = "V";
                                            String strFirmWareVersion = "V";
                                            int packageLen;
                                            strHardWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strHardWareVersion += Integer.toString(bResultArray[index++] & 0xFF);
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF);
                                            packageLen = bResultArray[index++] & 0xFF;
                                            if (device != null) {
                                                Log.e("linvisf", "设备：" + device.getName() + "，固件信息：硬件版本号 = " + strHardWareVersion + ", 固件版本号 = " + strFirmWareVersion);
                                            }
//                                            Version version = new Version();
//                                            version.setHardVersion(strHardWareVersion);
//                                            version.setFirmVersion(strFirmWareVersion);
//                                            version.setPackageLen(packageLen);
//
//                                            serialPortPackage.setData(version);
                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                    }
                                    break;

                                case 0x00: //查询命令
                                    switch (cmdSub) {
                                        case 0x00: //查询版本
                                            String strHardWareVersion = "V";
                                            String strFirmWareVersion = "V";
                                            strHardWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strHardWareVersion += Integer.toString(bResultArray[index++] & 0xFF);
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF) + ".";
                                            strFirmWareVersion += Integer.toString(bResultArray[index++] & 0xFF);
                                            if (device != null) {
                                                Log.e("linvisf", "设备：" + device.getName() + "，固件信息：硬件版本号 = " + strHardWareVersion + ", 固件版本号 = " + strFirmWareVersion);
                                            }
//                                            Version version = new Version();
//                                            version.setHardVersion(strHardWareVersion);
//                                            version.setFirmVersion(strFirmWareVersion);
//                                            Log.i("as","===============查询版本=============");
//                                            serialPortPackage.setData(version);
                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                        case 0x03://查询电池状态
//                                            BatteryBean batteryBean = new BatteryBean();
//                                            batteryBean.setBatteryStatus(bResultArray[index++] & 0xFF);
//                                            batteryBean.setStatus(bResultArray[index++] & 0xFF);
//                                            batteryBean.setPower(bResultArray[index++] & 0xFF);
//                                            serialPortPackage.setData(batteryBean);
//                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;

                                        case 0x01://查询系统参数的用户配置
//                                            SystemConfig config = new SystemConfig();
//                                            config.setStartPosition((bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF));
//                                            config.setRunTotal((bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF));
//                                            config.setMaxAD(bResultArray[index++] & 0xFF);
//                                            config.setScanTime(bResultArray[index++] & 0xFF);
//                                            config.setTemp(((bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF)));
//                                            config.setTempSwitch(bResultArray[index++] & 0xFF);
//                                            config.setDebugSwitch(bResultArray[index++] & 0xFF);
//
//                                            Global.getInstance().setConfig(config);
//                                            Log.i("as", "Protocol:查询系统参数的用户配置:" + config.getTemp());
//                                            Log.i("as", "Protocol:查询系统参数的用户配置温度开关:"
//                                                    + (config.getTempSwitch() == 0 ? "关" : "开"));
//
//                                            serialPortPackage.setData(config);
//                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));

                                            break;
                                        case 0x02://查询系统参数的用户配置
                                            String sn = "";
                                            int length = bResultArray[index++] & 0xFF;
                                            if (length > 0) {
                                                byte[] bCodeArray = Arrays.copyOfRange(bResultArray, index++, bResultArray.length - 2);

                                                try {
                                                    sn = new String(bCodeArray, "GBK").trim();
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            Log.e("as", "sn=====:" + sn);
                                            if (device != null) {
                                                Log.e("linvisf", "设备：" + device.getName() + "，SN码 = " + sn);
                                            }
                                            serialPortPackage.setData(sn);
                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));

                                            break;
                                    }
                                    break;

                                case 0x11: //测量相关命令
                                    switch (cmdSub) {
                                        case 0x00: //试剂卡状态
                                            int state = bResultArray[index++] & 0xFF;
                                            serialPortPackage.setData(state);
                                            if (device != null) {
                                                Log.e("linvisf", "设备：" + device.getName() + "，试剂卡的状态 = " + (state == 0 ? "不在位": "在位"));
                                            }
                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                        case 0x02: //扫码
                                            byte[] bCodeArray = Arrays.copyOfRange(bResultArray, index++, bResultArray.length - 2);
                                            String strBarCode = "";
                                            try {
                                                strBarCode = new String(bCodeArray, "GBK").trim();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            serialPortPackage.setData(strBarCode);
                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                        case 0x03: //光电采集A

                                            int num = bResultArray[index++] & 0xFF;
                                            Log.e("F400","包序号 === " + num);
                                            if (device != null) {
                                                Log.e("linvisf", "设备：" + device.getName() + "，采集指令 包序号 === " + num);
                                            }
                                            // 11 03指令发送包序号
                                            Protocol.sendACK(context, device, cmd, cmdSub, packNumber, (byte) num);
                                            int count = (bResultArray[index++] & 0xFF);
                                            Log.e("count-->", count + "");
                                            int[] iDataArray = new int[count];
                                            for (int i = 0; i < iDataArray.length; i++) {
                                                iDataArray[i] = (bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF);
                                            }
//                                            TemCollectDataBean collectDataBean = new TemCollectDataBean();
//                                            collectDataBean.setNum(num);
//                                            collectDataBean.setData(iDataArray);
//
//                                            serialPortPackage.setData(collectDataBean);
//                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                        case 0x04: //读取ID卡
                                            // 以前逻辑
//                                            int dataCount = (bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF);
//                                            Log.e("dataCount-->", dataCount + "");
//                                            byte[] idCardArray = Arrays.copyOfRange(bResultArray, index, bResultArray.length - 2);
////                                        byte[] idCardArray = new byte[dataCount];
////                                        for (int i = 0; i < idCardArray.length; i++) {
////                                            idCardArray[i] = bResultArray[index++];
////                                        }
//                                            serialPortPackage.setData(idCardArray);

                                            int idNum = bResultArray[index++] & 0xFF;
                                            Protocol.sendACK(context, device, cmd, cmdSub, packNumber, (byte) idNum);
                                            int idCount = (bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF);
                                            Log.e("count-->", idCount + "");
                                            byte[] idCardArray = new byte[idCount];
                                            for (int i = 0; i < idCardArray.length; i++) {
                                                idCardArray[i] = bResultArray[index++];
                                            }
//                                            TemIdChipBean temIdChipBean = new TemIdChipBean();
//                                            temIdChipBean.setNum(idNum);
//                                            temIdChipBean.setData(idCardArray);
//                                            serialPortPackage.setData(temIdChipBean);
//
//                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                    }
                                    break;

                                case 0x12://维护指令
                                    switch (cmdSub) {
                                        case 0x08:
                                            int temp = (bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF);//加热片温度
                                            int temp2 = 0;//环境温度
                                            if (bResultArray.length == 16) {
                                                temp2 = (bResultArray[index++] & 0xFF) << 8 | (bResultArray[index++] & 0xFF);
                                            }

                                            Log.e("temp", "加热片温度：" + temp + ",环境温度：" + temp2);
                                            //eventbus发送温度
//                                            TempBean tempBean = new TempBean();
//                                            float t = ArithUtil.round(ArithUtil.mul(temp, 0.1f), "#.00");
//                                            tempBean.setHeadTemp(t);
//                                            tempBean.setEnvirTemp(temp2);
//                                            serialPortPackage.setData(tempBean);
//                                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_DATA_PACKAGE, serialPortPackage));
                                            break;
                                    }
                                    break;
                                default:
                            }

                        } else if (packType == 0x05) {//报告包
                            Log.e("DO", ".......Get Report Package.");
                            Protocol.sendACK(context, device, cmd, cmdSub, packNumber, (byte) 0x00);
                            byte bResult = bResultArray[index++];
                            serialPortPackage.setResult(bResult);
                            EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_PORT_REPORT_PACKAGE, serialPortPackage));
                        }
                        isStartGet = false;// 本帧数据接收并处理完毕
                        try {
                            result = result.substring((len + 4) * 2, result.length());//
                        } catch (Exception e) {
                            Log.e("DO", ".......出现异常=======" + e.getMessage());
                            return;
                        }
                    }
                } else {
                    return;
                }
            }
        }
    }
}
